package pulpfizz.pulp;

import org.jbox2d.collision.AABB;
import org.jbox2d.common.Vec2;

import pulpcore.Stage;
import pulpcore.animation.BindFunction;
import pulpcore.animation.Fixed;
import pulpcore.animation.Property;
import pulpcore.sprite.Group;
import pulpfizz.physics.NewWorld;

public class PhysicsGroup extends Group
{
	private NewWorld world;
	float scaling = 20f;
	
	Fixed physicsWidth;
	Fixed physicsHeight;
	
	public PhysicsGroup(double x, double y, double w, double h)
	{
		super(x,y,w,h);
		
		world = new NewWorld();

		physicsWidth = new Fixed();
		physicsHeight = new Fixed();
		physicsWidth.bindTo(new BindFunction() {
			public Number f()
			{
				return width.get() / scaling;
			}
		});
		physicsHeight.bindTo(new BindFunction() {
			public Number f()
			{
				return height.get() / scaling;
			}
		});

		width.addListener(this);
		height.addListener(this);
		
		setDefaultGravity();
	}


	@Override
	public void update(int elapsedTime)
	{
		super.update(elapsedTime);
		
		int fr = Stage.getFrameRate();
		world.update((int) (1000.0f / fr));
	}

	/** @return the scaling */
	public float getScaling()
	{
		return scaling;
	}

	/**
	 * @param scaling the scaling to set
	 */
	public void setScaling(float scaling)
	{
		this.scaling = scaling;
	}

	
	public void setDefaultGravity()
	{
		world.setGravity(new Vec2(0, -9.8f));
	}

	public NewWorld getWorld()
	{
		return world;
	}
	
	private void expandAABB()
	{
		if (world == null)
			return;
		AABB bounds = new AABB(new Vec2(0,0),
			   new Vec2((float)physicsWidth.get(),(float)physicsHeight.get()));
	}
	
	@Override
	public void propertyChange(Property property)
	{
		super.propertyChange(property);
		
		if (property == width || property == height)
		{
			expandAABB();
		}
	}

}
